package com.xykj.enterprise.wechat.event.service;

import com.alibaba.fastjson.JSONArray;
import com.xykj.enterprise.wechat.bean.ext.externalcontact.GroupChatInfo;
import com.xykj.enterprise.wechat.bean.ext.externalcontact.GroupChatMemberInfo;
import com.xykj.enterprise.wechat.bean.ext.externalcontact.GroupChatVo;
import com.xykj.enterprise.wechat.core.dao.CorpExtDao;
import com.xykj.enterprise.wechat.core.dao.GroupChatDao;
import com.xykj.enterprise.wechat.core.dao.GroupChatMemberDao;
import com.xykj.enterprise.wechat.core.model.dodb.CorpExt;
import com.xykj.enterprise.wechat.core.model.dodb.GroupChat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author george
 * @create 2021-04-22 14:00
 */
@Slf4j
@Service
public class GroupChatServiceImpl implements GroupChatService {

    @Autowired
    private GroupChatDao groupChatDao;
    @Autowired
    private CorpExtDao corpExtDao;
    @Autowired
    private GroupChatMemberDao groupChatMemberDao;

    @Override
    public void save(String corpid, GroupChatVo vo) {
        GroupChatInfo info = vo.getGroup_chat();
        GroupChat chat = groupChatDao.get(corpid, info.getChat_id());
        if (chat == null) {
            // 新增
            groupChatDao.save(
                    corpid,
                    info.getChat_id(),
                    info.getName(),
                    info.getOwner(),
                    info.getNotice(),
                    info.getAdmin_list() == null ? null : JSONArray.toJSON(info.getAdmin_list()).toString()
            );
        } else {
            // 修改
            groupChatDao.update(
                    chat.getId(),
                    corpid,
                    info.getChat_id(),
                    info.getName(),
                    info.getOwner(),
                    info.getNotice(),
                    info.getAdmin_list() == null ? null : JSONArray.toJSON(info.getAdmin_list()).toString()
            );
        }

        // 群成员同步
        groupChatMemberDao.delete(chat.getChatId(), corpid);
        List<GroupChatMemberInfo> members = info.getMember_list();
        for (GroupChatMemberInfo i : members) {
            groupChatMemberDao.save(
                    chat.getChatId(),
                    corpid,
                    i.getUserid(),
                    String.valueOf(i.getType()),
                    null,
                    String.valueOf(i.getJoin_scene()),
                    String.valueOf(i.getJoin_time()),
                    null
            );
        }


    }

    @Override
    public void syncSucc(String corpid) {
        corpExtDao.syncGroupChatData(corpid, CorpExt.SUCC);
    }
}
